import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import http from '@/utils/http';
import { useUserStore } from './user';

export const useTemplateStore = defineStore('template', () => {
  const userStore = useUserStore();
  
  const templates = ref([]);
  const currentTemplate = ref(null);
  const loading = ref(false);
  const error = ref(null);
  const totalTemplates = ref(0);

  // 获取模板列表
  const fetchTemplates = async (page = 1, size = 10, category = null) => {
    try {
      loading.value = true;
      error.value = null;
      
      const payload = { current: page, pageSize: size };
      if (category) {
        payload.category = category;
      }
      
      const response = await http.post('/documentTemplate/list/page/vo', payload);
      
      templates.value = response.data.records;
      totalTemplates.value = response.data.total;
    } catch (err) {
      console.error('Failed to fetch templates:', err);
      error.value = '获取模板列表失败';
    } finally {
      loading.value = false;
    }
  };

  // 获取模板详情
  const fetchTemplateById = async (id) => {
    try {
      loading.value = true;
      error.value = null;
      
      // 确保id是有效的数字
      if (!id || isNaN(Number(id)) || Number(id) <= 0) {
        throw new Error('无效的模板ID');
      }
      
      const response = await http.get(`/documentTemplate/get/vo`, {
        params: { id: Number(id) }
      });
      
      currentTemplate.value = response.data;
      return response.data;
    } catch (err) {
      console.error(`Failed to fetch template ${id}:`, err);
      error.value = '获取模板详情失败';
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 创建新模板
  const createTemplate = async (name, content, category) => {
    try {
      loading.value = true;
      error.value = null;
      
      const payload = {
        name,
        content,
        category
      };
      
      // 获取当前登录用户ID
      if (userStore.currentUser && userStore.currentUser.id) {
        payload.userId = userStore.currentUser.id;
      }
      
      const response = await http.post('/documentTemplate/add', payload);
      
      // 刷新模板列表
      await fetchTemplates();
      
      return response.data;
    } catch (err) {
      console.error('Failed to create template:', err);
      error.value = '创建模板失败';
      return null;
    } finally {
      loading.value = false;
    }
  };

  // 更新模板
  const updateTemplate = async (id, updates) => {
    try {
      loading.value = true;
      error.value = null;
      
      const response = await http.post(`/documentTemplate/update`, {
        id,
        ...updates
      });
      
      // 如果当前正在查看的模板被更新，则更新当前模板
      if (currentTemplate.value && currentTemplate.value.id === id) {
        currentTemplate.value = { ...currentTemplate.value, ...updates };
      }
      
      // 更新模板列表中的模板
      const index = templates.value.findIndex(tpl => tpl.id === id);
      if (index !== -1) {
        templates.value[index] = { ...templates.value[index], ...updates };
      }
      
      return true;
    } catch (err) {
      console.error(`Failed to update template ${id}:`, err);
      error.value = '更新模板失败';
      return false;
    } finally {
      loading.value = false;
    }
  };

  // 删除模板
  const deleteTemplate = async (id) => {
    try {
      loading.value = true;
      error.value = null;
      
      await http.post(`/documentTemplate/delete`, { id });
      
      // 从列表中移除被删除的模板
      templates.value = templates.value.filter(tpl => tpl.id !== id);
      
      // 如果当前正在查看的模板被删除，则清空当前模板
      if (currentTemplate.value && currentTemplate.value.id === id) {
        currentTemplate.value = null;
      }
      
      return true;
    } catch (err) {
      console.error(`Failed to delete template ${id}:`, err);
      error.value = '删除模板失败';
      return false;
    } finally {
      loading.value = false;
    }
  };

  return {
    templates,
    currentTemplate,
    loading,
    error,
    totalTemplates,
    fetchTemplates,
    fetchTemplateById,
    createTemplate,
    updateTemplate,
    deleteTemplate
  };
});